﻿using FishNet.Component.Observing;
using FishNet.Connection;
using GameBasic;
using System.Collections.Generic;
using UnityEngine;

namespace VCity
{
    public class NetServer : MonoSingleton<NetServer>
    {
        Dictionary<int, NetLoginData> loginDatas;

        public int matchPlayerSize = 32;

        protected override void Awake()
        {
            base.Awake();

            loginDatas = new ();
        }

        private void Start()
        {
            NetworkMain.Instance.networkManager.SceneManager.OnClientLoadedStartScenes += SceneManager_OnClientLoadedStartScenes;
        }

        private void SceneManager_OnClientLoadedStartScenes(NetworkConnection connection, bool asServer)
        {
            if (loginDatas.TryGetValue(connection.ClientId, out var data))
            {
                loginDatas.Remove(connection.ClientId);

                // spawn player
                var netMain = NetworkMain.Instance;
                var networkManager = netMain.networkManager;

                //
                var player = Instantiate(netMain.playerPrefab);
                player.name = $"Player_{connection.ClientId}";
                player.skin = data.skin;
                player.nickName = data.username;
                networkManager.ServerManager.Spawn(player.gameObject, connection);
            }
        }

        public void OnLogin(NetworkConnection connection, NetLoginData data)
        {
            // 
            loginDatas[connection.ClientId] = data;

            // match
            //var networkManager = NetworkMain.Instance.networkManager;
            //MatchCondition.AddToMatch(, connection);

            // add 
            var matchs = MatchCondition.MatchConnections;
            int matchId = -1;
            int maxId = -1;
            foreach (var match in matchs)
            {
                maxId = Mathf.Max(maxId, match.Key);

                int playerCount = match.Value.Count;
                if (playerCount < matchPlayerSize)
                {
                    matchId = match.Key;
                    break;
                }
            }
            matchId = matchId == -1 ? maxId + 1 : matchId;

            MatchCondition.AddToMatch(matchId, connection);

            //Debug.Log($"Server: player_{connection.ClientId} join match_{matchId}({matchs[matchId].Count})");
        }
    }
}